4
4
.
.
3
3
.
.
1
1
@
@
W
W
e
e
b
b
M
M
v
v
c
c
T
T
e
e
s
s
t
t
I
I
n
n
f
f
o
o
[
[
G
G
]
]
[
[
R
R
]
]
This tutorial shows how to use @WebMvcTest which
creates Application Context that only contains Beans needed for testing web Controllers
instantiates MockMvc (as one such Bean)
This means that @WebMvcTest for example will instantiate Classes that are Annotated with @Controller.
This means that you can use @Autowired MyController myController to inject Instance of MyController.
But @WebMvcTest for example will not instantiate Classes that are Annotated with @Entity.
This means that you can't use @Autowired PersonEntity personEntity to inject Instance of PersonEntity.
However you can use @MockBean or manually instantiate Classes that are not automatically pulled into Context.
Purpose of @WebMvcTest is to keep tests faster than when using @SpringBootTest which loads everything into Context.
But to also allow you to add additional instances if needed to fine tune your tests.
Application Schema [Result]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: Controller Annotations, Tomcat Server
Syntax
@WebMvcTest
class MyControllerTest {
@Autowired MockMvc mockMvc;
@Autowired MyController myController;
http://localhost:8080/Hello
Tomcat
hello()
MyController
MyControllerTest
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_test_mockmvc (add Spring Boot Starters from the table)
Create Package: controllers (inside main package)
Create Class: MyController.java (inside controllers package)
Create Test Class: MyControllerTest.java
MyController.java
package com.ivoronline.springboot_test_mockmvc_webmvctest.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/Hello")
public String hello() {
return "Hello from Controller";
}
}
MyControllerTest.java
package com.ivoronline.springboot_test_mockmvc_webmvctest.controllers;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest
class MyControllerTest {
@Autowired MockMvc mockMvc;
@Autowired MyController myController;
@Test
void hello() throws Exception {
mockMvc.perform(get("/Hello"))
.andExpect(status().isOk());
}
}
R
R
e
e
s
s
u
u
l
l
t
t
http://localhost:8080/Hello
Run Test Class: MyControllerTest.java
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>